package com.heihei.security.service.auth;

import com.heihei.security.dto.auth.UserDto;
import com.heihei.security.model.auth.AuthenticationRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 用户认证
 *
 * @author duanhengfei
 * @version 1.0
 * @date 2020/6/27 17:59
 * @since JDK1.8
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    /**
     * 用户认证，校验用户信息是否合法
     *
     * @author duanhengfei
     * @date 2020年06月27日 18:00:15
     */
    @Override
    public UserDto authentication(AuthenticationRequest authenticationRequest) {
        if(authenticationRequest == null || StringUtils.isEmpty(authenticationRequest.getUsername()) || StringUtils.isEmpty(authenticationRequest.getPassword())) {
            throw new RuntimeException("账号密码不能为空");
        }
        //模拟数据库查询
        UserDto userDto = getUserDto(authenticationRequest.getUsername());
        if(userDto == null) {
            throw new RuntimeException("查询不到该用户");
        }
        if(!authenticationRequest.getPassword().equals(userDto.getPassword())) {
            throw new RuntimeException("账号或密码错误");
        }
        //认证通过，返回用户的身份信息
        return userDto;
    }

    /**
     * 模拟用户查询
     *
     * @author duanhengfei
     * @date 2020年06月27日 18:04:04
     */
    public UserDto getUserDto(String username) {
        return userMap.get(username);
    }

    private Map<String, UserDto> userMap = new HashMap<String, UserDto>();
    {
        Set<String> auth01 = new HashSet<>();
        auth01.add("p1");  //对应 /resource/r1 资源
        Set<String> auth02 = new HashSet<>();
        auth02.add("p2");  //对应 /resource/r2 资源
        userMap.put("zhangsan", new UserDto("1010", "zhangsan", "123456", "18437960517", "张三", auth01));
        userMap.put("lisi", new UserDto("1011", "lisi", "123456", "18437960601", "李四", auth02));

    }


}